<template>
  <Card dis-hover :bordered="false">
    <Row class="ivu-mb-16">
      <Col span="22">
        <Form inline :label-width="0">
          <FormItem>
            <DatePicker
              v-model="params.date"
              type="daterange"
              :options="options"
              placeholder="创建日期选择"
              @on-change="searchData"
            />
          </FormItem>
          <FormItem>
            <Select
              placeholder="请选择项目"
              v-model="params.project_ids"
              :filterable="projectList.length >= 10"
              multiple
              @on-clear="searchData"
              @on-change="searchData"
              clearable
            >
              <Option
                v-for="item in projectList"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem>
            <Select
              placeholder="标签筛选"
              v-model="params.tag_ids"
              multiple
              :filterable="tagList.length >= 10"
              clearable
              @on-change="searchData"
            >
              <Option
                v-for="item in tagList"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem>
            <Input
              placeholder="名称/简介/文件名"
              v-model="params.keyword"
              @on-clear="searchData"
              @on-enter="searchData"
              clearable
            />
          </FormItem>
          <FormItem>
            <Select
              placeholder="请选择创建人"
              v-model="params.created_member_id"
              multiple
              :filterable="userList.length >= 10"
              clearable
              @on-change="searchData"
            >
              <Option
                v-for="item in userList"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
        </Form>
      </Col>
      <Col span="2" style="text-align: right">
        <Button
          type="primary"
          @click="handleAdd"
          v-hasC="{
            name: 'v1-buss-tool-create',
            flag: 'v1/buss/tool/create',
          }"
          >新增</Button
        >
      </Col>
    </Row>

    <Table
      :columns="columns"
      :data="list"
      :loading="loading"
      @on-sort-change="sortChange"
      :max-height="tableHeigth"
    >
      <template #tag="{ row }">
        <Tooltip placement="top">
          <template v-for="(item, index) in row.tag_arr">
            <Tag color="default" v-if="index < 3">{{ item }}</Tag>
          </template>
          <template #content>
            <Tag color="default" v-for="item in row.tag_arr">{{ item }}</Tag>
          </template>
        </Tooltip>
        <!-- <Tag color="default" v-for="item in row.tag_arr">{{ item }}</Tag> -->
      </template>
      <template #name="{ row }">
        <a :href="row.url" target="_blank" v-if="row.url">{{ row.name }}</a>
        <span v-else>{{ row.name }}</span>
      </template>
      <template #preview_image="{ row }">
        {{ row.preview_image ? row.preview_image.length : 0 }}
      </template>
      <template #file_name="{ row }">
        <a
          :href="row.file_url + '?auth_access_token=' + access_token"
          v-if="row.file_name"
          target="_blank"
          :download="row.file_name"
        >
          {{ row.file_name }}
        </a>
      </template>
      <template #action="{ row }">
        <a
          @click="showImg(row.preview_image)"
          v-if="row.preview_image.length > 0"
          >预览</a
        >
        <a disabled="true" v-else>预览</a>
        <Divider
          type="vertical"
          v-hasC="{
            name: 'v1-buss-tool-update',
            flag: 'v1/buss/tool/update',
          }"
        />
        <a
          @click="handleEdit(row)"
          v-hasC="{
            name: 'v1-buss-tool-update',
            flag: 'v1/buss/tool/update',
          }"
          >编辑</a
        >
        <Divider
          type="vertical"
          v-hasC="{
            name: 'v1-buss-tool-update',
            flag: 'v1/buss/tool/update',
          }"
        />
        <a
          @click="handleDel(row.id)"
          class="del"
          v-hasC="{
            name: 'v1-buss-tool-delete',
            flag: 'v1/buss/tool/delete',
          }"
          >删除</a
        >
      </template>
    </Table>
    <Page
      class="ivu-mt-16"
      :total="total"
      :modelValue="params.current"
      :page-size="params.size"
      :page-size-opts="pageOpts"
      show-total
      show-sizer
      @on-change="changePage"
      @on-page-size-change="changepageSize"
    />
    <Modal
      :mask-closable="false"
      v-model="addModal"
      :title="edit ? '新增' : '编辑'"
      :footer-hide="true"
      :draggable="true"
      @on-visible-change="
        (e) => {
          !e && haddleCancel();
        }
      "
    >
      <Form ref="create" :model="toolInfo" :rules="rules" :label-width="70">
        <FormItem label="名称" prop="name" required>
          <Input
            v-model="toolInfo.name"
            placeholder="请输入名称"
            :maxlength="30"
          />
        </FormItem>
        <FormItem label="项目" prop="project_id" required>
          <Select
            v-model="toolInfo.project_id"
            placeholder="请选择项目"
            :filterable="projectAddList.length >= 10"
            @on-open-change="showAll"
            clearable
          >
            <Option
              v-for="item in projectAddList"
              :value="+item.value"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="网址" prop="url">
          <Input v-model="toolInfo.url" placeholder="请输入网址" />
        </FormItem>
        <FormItem label="简介说明" prop="desc">
          <Input
            v-model="toolInfo.desc"
            placeholder="简单明了直击主题"
            :maxlength="50"
          />
        </FormItem>
        <FormItem label="标签" prop="tagIds">
          <Select
            placeholder="请选择标签"
            multiple
            filterable
            allow-create
            @on-open-change="openChange"
            @on-change="tagChange"
            ref="tags"
            v-model="toolInfo.tagIds"
          >
            <Option
              v-for="item in tagAddList"
              :value="isNaN(item.value) ? item.value : parseInt(item.value)"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="上传附件" prop="file">
          <Upload
            :action="fileUrl"
            :accept="supportType"
            :show-upload-list="false"
            :before-upload="handleBeforeUpload"
            :on-error="handleUploadError"
          >
            <Button type="primary" :loading="loadingUpload">上传</Button>
            <Tooltip
              :max-width="300"
              placement="top"
              :content="'支持文件格式：' + supportType"
              class="ivu-ml-8"
            >
              <Icon type="ios-alert-outline" size="20" color="#2db7f5" />
            </Tooltip>
          </Upload>
          <Progress
            v-if="progress && progress != 100"
            :percent="progress"
            :stroke-width="5"
          />
          <ul class="ivu-upload-list">
            <li
              class="ivu-upload-list-file ivu-upload-list-file-finish"
              style="display: inline-block"
              v-for="item in files"
              :key="item.url"
            >
              <span><Icon type="ios-document-outline" /> {{ item.name }}</span>
              <i
                class="ivu-icon ivu-icon-ios-close ivu-upload-list-remove"
                style=""
                @click="handleRemove()"
              ></i>
            </li>
          </ul>
        </FormItem>
        <FormItem label="预览图" prop="imgfiles">
          <Upload
            :action="fileUrl"
            :accept="supportImg"
            multiple
            :show-upload-list="false"
            :before-upload="imgBeforeUpload"
            :on-error="imgUploadError"
          >
            <Button
              type="primary"
              :loading="loadingImgUpload"
              @click="showMaxSize = true"
              >上传</Button
            >
            <Tooltip
              :max-width="300"
              placement="top"
              :content="'支持图片格式：' + supportImg"
              class="ivu-ml-8"
            >
              <Icon type="ios-alert-outline" size="20" color="#2db7f5" />
            </Tooltip>
          </Upload>
          <div class="imgList ivu-mt-16">
            <div
              class="demo-upload-list"
              v-for="(item, index) in toolInfo.imgfiles"
              :key="item.url"
            >
              <img :src="item.url" fit="cover" width="40" height="40" />
              <div class="demo-upload-list-cover">
                <Icon type="ios-eye-outline" @click="handleView(index)"></Icon>
                <Icon
                  type="ios-trash-outline"
                  @click="handleImgRemove(item)"
                ></Icon>
              </div>
            </div>
          </div>
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: right">
        <Button type="default" @click="haddleCancel">取消</Button>
        <Button
          type="primary"
          @click="ok"
          style="margin-left: 10px"
          :loading="btnLoading"
          >确定</Button
        >
      </div>
    </Modal>
  </Card>
</template>
<script>
import dayjs from "dayjs";
import Setting from "@/setting";
import util from "@/libs/util";
import {
  toolList,
  createTool,
  deleteTool,
  toolInfo,
  updateTool,
  checkTgaStatus,
  uploadFile,
  uploadImg,
} from "@api/toolnavigation.js";
export default {
  name: "toolnavigation",
  data() {
    return {
      access_token: util.cookies.get("token"),
      fileUrl: "",
      tableHeigth: document.body.clientHeight - 280,
      addModal: false,
      edit: true,
      loading: false,
      btnLoading: false,
      tagList: [],
      fileList: [],
      userList: [],
      files: [],
      loadingUpload: false,
      loadingImgUpload: false,
      extendData: { site: "tool", module: "nav" },
      supportType: "",
      supportImg: "",
      tagAddList: [],
      projectAddList: [],
      projectList: [],
      params: {
        date: [],
        current: 1,
        size: 10,
        tag_ids: [],
        keyword: "",
        created_member_id: [],
        status: "",
        order_column: "",
        order_sort: "",
        project_ids: [],
      },
      total: 0,
      pageOpts: [10, 20, 30, 40],
      columns: [
        {
          slot: "name",
          title: "名称",
          width: 160,
        },
        {
          key: "desc",
          title: "简介说明",
          minWidth: 150,
        },
        {
          key: "project_name",
          title: "项目",
          width: 100,
        },
        {
          slot: "tag",
          title: "标签",
          ellipsis: "true",
          tooltip: "true",
          minWidth: 120,
        },
        {
          slot: "file_name",
          title: "文件",
          minWidth: 120,
        },
        {
          key: "file_size",
          title: "文件大小",
          width: 120,
        },
        {
          slot: "preview_image",
          title: "预览图数量",
          width: 110,
        },
        {
          key: "created_member_name",
          title: "创建人",
          width: 100,
        },
        {
          key: "created_at_str",
          title: "创建日期",
          width: 120,
          sortable: "custom",
        },
        {
          key: "updated_at_str",
          title: "更新日期",
          width: 120,
          sortable: "custom",
        },
        {
          slot: "action",
          title: "操作",
          width: 160,
          fixed: "right",
        },
      ],
      list: [],
      toolInfo: {
        id: "",
        name: "",
        project_id: "",
        url: "",
        desc: "",
        tag_ids: [],
        tagIds: [],
        file: "",
        imgfiles: [],
      },
      options: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        },
      },
      rules: {
        name: [{ required: true, message: "请输入名称" }],
        project_id: [{ required: true, message: "请选择项目" }],
      },
      newTag: "",
      newTagId: "",
      initTagList: [],
      tags: [],
      controller: null,
      progress: 0,
      controller1: null,
      maxFiles: 10,
      filesNum: [],
      showMaxSize: false,
    };
  },
  mounted() {
    this.fileUrl =
      Setting.request.apiBaseURL +
      `/common/file/upload?auth_access_token=${util.cookies.get("token")}`;
    this.getData();
  },
  watch: {
    tags(newData, oldData) {
      if (newData.length > oldData.length) {
        let flag = false;
        let hasTags = false;
        this.tagAddList.forEach((item) => {
          if (
            newData[newData.length - 1] == item.value ||
            newData[newData.length - 1] == item.label
          ) {
            flag = true;
            this.toolInfo.tagIds[this.toolInfo.tagIds.length - 1] = isNaN(
              item.value
            )
              ? item.value
              : parseInt(item.value);
            this.toolInfo.tagIds = [...new Set(this.toolInfo.tagIds)];
            return;
          }
        });
        if (!flag) {
          checkTgaStatus({ name: newData[newData.length - 1], type: 2 }).then(
            (res) => {
              if (res.res) {
                this.tagAddList.push({
                  value: isNaN(newData[newData.length - 1])
                    ? newData[newData.length - 1]
                    : parseInt(newData[newData.length - 1]),
                  label: newData[newData.length - 1],
                });
                this.toolInfo.tagIds[this.toolInfo.tagIds.length - 1] = isNaN(
                  newData[newData.length - 1]
                )
                  ? newData[newData.length - 1]
                  : parseInt(newData[newData.length - 1]);
                hasTags = true;
                return;
              }
              if (!hasTags) {
                let tagIds = JSON.parse(JSON.stringify(this.toolInfo.tagIds));
                tagIds.pop();
                this.toolInfo.tagIds = tagIds;
                this.$Message.success("此标签已被禁用！");
              }
            }
          );
        }
      }
    },
  },
  methods: {
    showImg(imgArr) {
      if (imgArr.length > 0) {
        this.$hevueImgPreview({
          multiple: true,
          imgList: imgArr,
        });
      }
    },
    showAll(e) {
      if (e) {
        let downList = document.querySelectorAll(
          ".ivu-select-dropdown-list .ivu-select-item"
        );
        downList.forEach((item) => {
          item.style.display = "block";
        });
      }
    },
    handleBeforeUpload(e) {
      if (e.size > 2 * 1024 * 1024 * 1024) {
        this.$Message.error("文件大小不能超过2G");
        return false;
      }
      this.loadingUpload = true;
      this.controller = new AbortController();
      this.progress = 0;
      this.files = [];
      this.toolInfo.file = null;
      uploadFile({ site: "tool", module: "nav", file: e }, this)
        .then((res) => {
          this.toolInfo.file = res.file;
          this.files = [e];
          this.loadingUpload = false;
        })
        .catch((res) => {
          this.loadingUpload = false;
        });
      return false;
    },
    handleUploadError(error, file, fileList) {
      this.$Message.error(error);
      this.loadingUpload = false;
    },
    imgBeforeUpload(e) {
      if (this.filesNum.length >= this.maxFiles) {
        if (this.showMaxSize) {
          this.$Message.success("图片数量不能超过" + this.maxFiles + "张！");
          this.showMaxSize = false;
        }
        return false;
      }
      if (e.size > 1024 * 1024 * 20) {
        this.$Message.error("文件大小不能超过20M");
        return false;
      }
      this.loadingImgUpload = true;
      this.filesNum.push(e);
      this.controller1 = new AbortController();
      uploadImg({ site: "tool", module: "preview_image", file: e }, this)
        .then((res) => {
          this.toolInfo.imgfiles.push(res);
          this.loadingImgUpload = false;
        })
        .catch((res) => {
          this.loadingImgUpload = false;
        });

      return false;
    },
    imgUploadError(error, file, fileList) {
      this.$Message.error(error);
      this.loadingImgUpload = false;
    },
    haddleCancel() {
      if (this.controller) {
        this.controller.abort();
        this.progress = 0;
      }
      if (this.controller1) {
        this.controller1.abort();
      }
      this.addModal = false;
    },
    handleView(index) {
      let imgArr = [];
      this.toolInfo.imgfiles.forEach((item) => {
        imgArr.push(item.url);
      });
      this.$hevueImgPreview({
        multiple: true,
        nowImgIndex: index,
        imgList: imgArr,
      });
    },
    handleImgRemove(file) {
      const fileList = this.toolInfo.imgfiles;
      this.toolInfo.imgfiles.splice(fileList.indexOf(file.file), 1);
      this.filesNum.splice(fileList.indexOf(file.file), 1);
    },
    handleRemove() {
      this.files = [];
      this.toolInfo.file = "";
    },
    searchData() {
      this.params.current = 1;
      this.getData();
    },
    //切换page
    changePage(index) {
      this.params.current = index;
      this.getData();
    },
    changepageSize(val) {
      this.params.size = val;
      this.getData();
    },
    handleDel(index) {
      this.$Modal.confirm({
        title: "删除提示",
        content: "是否确认删除此条记录，删除后不可恢复",
        onOk: () => {
          deleteTool({ id: index })
            .then(() => {
              this.$Message.success("删除成功");
              this.getData();
            })
            .catch(() => {});
        },
      });
    },
    initParams() {
      this.toolInfo = {
        id: "",
        name: "",
        project_id: "",
        url: "",
        desc: "",
        tag_ids: [],
        tagIds: [],
        file: "",
        imgfiles: [],
      };
      this.filesNum = [];
    },
    handleAdd() {
      this.files = [];
      toolInfo()
        .then((res) => {
          this.supportType = res.support_type.join(" , ");
          this.supportImg = res.support_image_type.join(" , ");
          this.tagAddList = [...res.condition.tag];
          this.initTagList = [...res.condition.tag];
          this.projectAddList = res.condition.project;
          this.initParams();
        })
        .catch(() => {});

      this.addModal = true;
      this.edit = true;
      this.$refs.create.resetFields();
    },
    handleEdit(info) {
      this.files = [];
      this.initParams();
      this.$refs.create.resetFields();
      toolInfo({ id: info.id })
        .then((res) => {
          this.supportType = res.support_type.join(" , ");
          this.supportImg = res.support_image_type.join(" , ");
          this.tagAddList = [...res.condition.tag];
          this.initTagList = [...res.condition.tag];
          this.projectAddList = res.condition.project;
          this.toolInfo = {
            id: res.id,
            name: res.name,
            project_id: res.project_id,
            url: res.url,
            desc: res.desc,
            file: res.file,
            imgfiles: [],
          };
          res.preview_image.forEach((item) => {
            this.filesNum.push({
              name: item.file,
              url: item.file_url,
            });
            this.toolInfo.imgfiles.push({
              file: item.file,
              url: item.file_url,
            });
          });
          this.files = res.file_name ? [{ name: res.file_name }] : [];
          this.toolInfo.tagIds = res.tag_ids;
          this.editProjectList = res.condition.project;
          this.editRoleList = res.condition.role;
          this.editDepartmentList = res.condition.department;
          this.editJobList = res.condition.job;
        })
        .catch(() => {});
      this.addModal = true;
      this.edit = false;
    },
    sortChange(e) {
      this.params.order_column = e.key.replace(/_str$/, "");
      this.params.order_sort = e.order;
      this.getData();
    },
    openChange(e) {
      if (!e) {
        this.$refs.tags.query = "";
      }
    },
    tagChange(e) {
      this.tags = this.toolInfo.tagIds;
    },
    getData() {
      this.loading = true;
      const params = {
        created_stime: this.params.date[0]
          ? dayjs(this.params.date[0]).format("YYYY-MM-DD")
          : "",
        created_etime: this.params.date[1]
          ? dayjs(this.params.date[1]).format("YYYY-MM-DD")
          : "",
        tag_ids: this.params.tag_ids,
        keyword: this.params.keyword,
        project_ids: this.params.project_ids,
        created_member_id: this.params.created_member_id,
        status: this.params.status,
        pageSize: this.params.size,
        page: this.params.current,
        order_column: this.params.order_column,
        order_sort: this.params.order_sort,
      };
      toolList(params)
        .then((res) => {
          this.userList = res.condition.created_member;
          this.projectList = res.condition.project;
          this.tagList = res.condition.tag;
          this.list = res.list;
          this.total = res.total;
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    addMember() {
      if (this.loadingUpload) {
        this.$Message.success("文件还在上传中请等待一会~");
        return;
      }
      this.btnLoading = true;
      let tagarr = [];
      this.toolInfo.tagIds.forEach((item) => {
        let hasTag = false;
        this.initTagList.forEach((el) => {
          if (item == el.value) {
            tagarr.push(el);
            hasTag = true;
            return;
          }
        });
        if (!hasTag) {
          tagarr.push({ value: 0, label: item });
        }
      });
      let preview_image = [];
      this.toolInfo.imgfiles.forEach((item) => {
        preview_image.push(item.file);
      });
      const params = {
        name: this.toolInfo.name,
        project_id: this.toolInfo.project_id,
        url: this.toolInfo.url,
        desc: this.toolInfo.desc,
        tags: tagarr,
        file: this.toolInfo.file,
        preview_image: preview_image,
      };
      if (this.edit) {
        createTool(params)
          .then((res) => {
            this.$Message.success("添加成功");
            this.addModal = false;
            this.btnLoading = false;
            this.params.current = 1;
            this.getData();
          })
          .catch(() => {
            this.btnLoading = false;
          });
      } else {
        updateTool(Object.assign({}, params, { id: this.toolInfo.id }))
          .then((res) => {
            this.$Message.success("编辑成功");
            this.addModal = false;
            this.btnLoading = false;
            this.getData();
          })
          .catch(() => {
            this.btnLoading = false;
          });
      }
    },
    ok() {
      this.$refs.create.validate((valid) => {
        if (valid) {
          this.addMember();
        } else {
          this.addModal = true;
          // this.$Message.error('填写错误，保存失败！')
          return;
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
:deep(.ivu-tooltip-inner) {
  white-space: normal !important;
  word-wrap: break-word;
}
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.imgList {
  width: 100%;
  white-space: nowrap;
  overflow: auto;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
